package com.jtlrm.ckd.mvp.view.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.base.sdk.base.net.CommonObserver;
import com.base.sdk.util.CommonUtil;
import com.github.promeg.pinyinhelper.Pinyin;
import com.hyphenate.chatuidemo.db.NewUserDao;
import com.hyphenate.chatuidemo.domain.NewUserEntity;
import com.jtlrm.ckd.R;
import com.jtlrm.ckd.base.acitvity.BaseActivity;
import com.jtlrm.ckd.entity.CreateGroupEntity;
import com.jtlrm.ckd.entity.GroupMemberEntity;
import com.jtlrm.ckd.entity.HuanZheEntity;
import com.jtlrm.ckd.entity.event.FinishPicWorker;
import com.jtlrm.ckd.entity.event.PicContactsMessage;
import com.jtlrm.ckd.entity.event.UpdateGroupMessage;
import com.jtlrm.ckd.entity.submitEntity.AddGroupMember;
import com.jtlrm.ckd.entity.submitEntity.CreateGroupData;
import com.jtlrm.ckd.mvp.model.SuiFangModel;
import com.jtlrm.ckd.mvp.model.dao.UserHelper;
import com.jtlrm.ckd.mvp.view.adapter.ContactsSeachAdapter;
import com.jtlrm.ckd.mvp.view.api.SelectInterface;
import com.jtlrm.ckd.util.ContactList.PicContactsView;
import com.jtlrm.ckd.util.ContactList.SlideBarEntity;
import com.jtlrm.ckd.util.EventBusUtil;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;

/**
 * 选择群成员
 */
public class PickContactsActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.pic_contacts_view)
    PicContactsView picContactsView;
    ListView listView;
    List<SlideBarEntity> slideBarEntities;
    @BindView(R.id.check_all)
    CheckBox allCheck;
    SuiFangModel suiFangModel;
    List<HuanZheEntity> userData = new ArrayList<>();
    @BindView(R.id.confirm)
    TextView confirmT;
    Set<String> select = new HashSet<>();
    HashSet<String> selectWork;
    String groupName;
    @BindView(R.id.search)
    EditText searchContent;
    ArrayList<GroupMemberEntity> memberEntities;
    String groupId;
    @BindView(R.id.back)
    ImageView backI;
    @BindView(R.id.person_sum)
    TextView personSumT;
    @BindView(R.id.content_container)
    RelativeLayout contentR;
    @BindView(R.id.recyclerView)
    RecyclerView searchR;
    @BindView(R.id.clear_search)
    ImageView clearSearchI;
    ContactsSeachAdapter seachAdapter;
    NewUserDao userDao = new NewUserDao();

    public static void goPic(Context context, String name) {
        Intent intent = new Intent(context, PickContactsActivity.class);
        intent.putExtra("name", name);
        context.startActivity(intent);
    }

    public static void goPic(Context context, String groupId, ArrayList<GroupMemberEntity> groupMemberEntities) {
        Intent intent = new Intent(context, PickContactsActivity.class);
        intent.putExtra("groupId", groupId);
        intent.putParcelableArrayListExtra("members", groupMemberEntities);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        groupName = getIntent().getStringExtra("name");
        memberEntities = getIntent().getParcelableArrayListExtra("members");
        groupId = getIntent().getStringExtra("groupId");
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentLayout() {
        setContentView(R.layout.activity_pick_contacts);
    }

    @Override
    protected void initView() {
        suiFangModel = new SuiFangModel();
        listView = picContactsView.getListView();
        @SuppressLint("InflateParams") View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.pic_contacts_header, null);
        HeaderItemClickListener clickListener = new HeaderItemClickListener();
        headerView.findViewById(R.id.my_worker_item).setOnClickListener(clickListener);
        listView.addHeaderView(headerView);
        seachAdapter = new ContactsSeachAdapter();
        searchR.setAdapter(seachAdapter);
        searchR.setLayoutManager(new LinearLayoutManager(context));
        searchR.addItemDecoration(createItemDecoration());
        EventBusUtil.register(this);
    }

    @Override
    protected void obtainData() {
    }

    @Override
    protected void initEvent() {
        allCheck.setOnClickListener(this);
        confirmT.setOnClickListener(this);
        loadData();
        searchContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                CommonUtil.hideSoftInput(context, searchContent);
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    search();
                }
                return false;
            }
        });
        backI.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkSearch()) {
                    finish();
                }
            }
        });
        searchContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String content = s.toString();
                if (notEmpty(content)) {
                    // 搜索
                    searchR.setVisibility(View.VISIBLE);
                    contentR.setVisibility(View.GONE);
                    search();
                } else {
                    // 未搜索
                    searchR.setVisibility(View.GONE);
                    contentR.setVisibility(View.VISIBLE);
                    updateCurrent();
                }
            }
        });
        clearSearchI.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkSearch();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK && !checkSearch())) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 判断搜索框是否有内容，如果没有返回true， 如果有范湖false并清除
     *
     * @return
     */
    private boolean checkSearch() {
        if (notEmpty(searchContent.getText() + "")) {
            setText(searchContent, "");
            CommonUtil.hideSoftInput(context, clearSearchI);
            return false;
        }
        return true;
    }


    private void updateCurrent() {
        Set<SlideBarEntity> existMembers = seachAdapter.getExistMembers();
        picContactsView.setExistMember(existMembers);
    }

    private void search() {
        if (slideBarEntities.size() == 0) {
            return;
        }
        String content = getTextStr(searchContent);
        if (!notEmpty(content)) {
            return;
        }
        String contentP = Pinyin.toPinyin(content, "").toLowerCase();
        List<SlideBarEntity> result = new ArrayList<>();
        for (SlideBarEntity entity : slideBarEntities) {
            if (entity.getPinyin().contains(contentP)) {
                result.add(entity);
            }
        }
        seachAdapter.setExistMembers(picContactsView.getExistMembers());
        seachAdapter.replaceData(result);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.check_all:
                if (allCheck.isChecked()) {
                    picContactsView.selectAll();
                } else {
                    picContactsView.clearAll();
                }
                break;
            case R.id.confirm:
                if (checkSearch()) {
                    updateData();
                }
                break;
        }
    }


    private void updateData() {
        if (notEmpty(searchContent.getText() + "")) {
            updateCurrent();
        }
        Set<SlideBarEntity> position = picContactsView.getExistMembers();
        select.clear();
        if (position != null) {
            for (SlideBarEntity integer : position) {
                select.add(integer.getuId());
            }
        }
        List<String> allSelect = new ArrayList<>();
        if (select != null) {
            allSelect.addAll(select);
        }
        if (selectWork != null) {
            allSelect.addAll(selectWork);
        }
        if (allSelect.size() == 0) {
            showToast("请选择成员");
            return;
        }
        showLoadingDialog("提交中");
        if (notEmpty(groupId)) {
            addMember(allSelect);
        } else {
            createGroup(allSelect);
        }

    }

    private void addMember(List<String> allSelect) {
        AddGroupMember data = new AddGroupMember(groupId, allSelect);
        suiFangModel.addGroupMember(data, new CommonObserver<Object>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                dismissLoadingDialog();
            }

            @Override
            public void onResult(Object data) {
                dismissLoadingDialog();
                showToast("添加成功");
                UpdateGroupMessage message = new UpdateGroupMessage();
                message.setUpdateMember(true);
                EventBusUtil.postEvent(message);
                finish();
            }
        }, lifecycleSubject);
    }

    private void createGroup(List<String> allSelect) {
        CreateGroupData data = new CreateGroupData(groupName, UserHelper.getInstance(context).getUserId(), allSelect);
        suiFangModel.createGroup(data, new CommonObserver<CreateGroupEntity>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                dismissLoadingDialog();
            }

            @Override
            public void onResult(CreateGroupEntity data) {
                dismissLoadingDialog();
                EventBusUtil.postEvent(new FinishPicWorker());
                showToast("创建成功");
                finish();
            }
        }, lifecycleSubject);
    }

    protected class HeaderItemClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.my_worker_item) {
                // 我的同事
                PicWorkerActivity.goPic(context, memberEntities, selectWork);
            }
        }
    }

    private void loadData() {
        showLoadingDialog("加载中");
        suiFangModel.queryHuanZheList(UserHelper.getInstance(context).getUserId()
                , new CommonObserver<List<HuanZheEntity>>() {

                    @Override
                    public void onError(int errType, String errMessage) {
                        showToast(errMessage);
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onResult(List<HuanZheEntity> data) {
                        userData.clear();
                        userData.addAll(data);
                        slideBarEntities = getSlideList(data);
                        picContactsView.init(slideBarEntities);
                        if (memberEntities != null) {
                            Set<String> memberIds = new HashSet<>();
                            Set<Integer> members = new HashSet<>();
                            for (int i = 0; i < data.size(); i++) {
                                if (existMember(data.get(i).getId())) {
                                    members.add(i);
                                    memberIds.add(data.get(i).getId());
                                }
                            }
                            if (members.size() > 0) {
                                picContactsView.setCantEditMembers(members);
                            }
                            if (memberIds.size() > 0) {
                                seachAdapter.setCantEditMembers(memberIds);
                            }
                        }
                        dismissLoadingDialog();
                        List<NewUserEntity> list = new ArrayList<>();
                        for (HuanZheEntity entity : data) {
                            NewUserEntity userEntity = new NewUserEntity();
                            userEntity.setUserId(entity.getId());
                            userEntity.setImId(entity.getEasemobId());
                            userEntity.setAvatar(entity.getHeadPicture());
                            userEntity.setName(entity.getName());
                            userEntity.setRole("2");
                            list.add(userEntity);
                        }
                        userDao.saveContactList(list);
                        picContactsView.setSelectInterface(new SelectInterface() {
                            @Override
                            public void selectResult(int result) {
                                updateSumPerson();
                            }
                        });
                    }
                }, lifecycleSubject);
    }

    public boolean existMember(String id) {
        if (memberEntities != null) {
            for (GroupMemberEntity entity : memberEntities) {
                if ((id + "").equals(entity.getId() + "")) {
                    return true;
                }
            }
        }
        return false;
    }

    public List<SlideBarEntity> getSlideList(List<? extends SlideBarEntity> list) {
        List<SlideBarEntity> data = new ArrayList<>();
        if (list != null) {
            for (SlideBarEntity entity : list) {
                data.add(entity);
            }
        }
        return data;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PicContactsMessage message) {
        if (message != null && !message.isUpdateWorker()) {
            selectWork = message.getWorkerId();
        }
        updateSumPerson();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtil.unregister(this);
    }


    /**
     * 更新选择人数
     */
    public void updateSumPerson() {
        int c = picContactsView.getExistMembers() == null ? 0 : picContactsView.getExistMembers().size();
        int w = selectWork == null ? 0 : selectWork.size();
        setText(personSumT, "共" + (c + w) + "人");
    }

    protected RecyclerView.ItemDecoration createItemDecoration() {
        return new DefaultItemDecoration(ContextCompat.getColor(this, R.color.margin_background), 2, 1, -1);
    }
}
